package hospital;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;

import com.example.test.R;

public class hospital_mycoupon extends Activity {
	
	private SharedPreferences sharedPref;
	TextView text;
    /** Called when the activity is first created. */
	//AlertDialog.Builder nologin;
	//AlertDialog.Builder coupon_use;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.hospital_mycoupon);
        
        
        text = (TextView) findViewById(R.id.mycoupon_sevicelife_text);
        
        if(quiz_answer_ok.check == 1)
        {
        	sharedPref = getSharedPreferences("pref",Activity.MODE_PRIVATE);
		//sharedEditor = sharedPref.edit();
		
        	int a = sharedPref.getInt("Month", 99);
        	int b = sharedPref.getInt("Day", 99);
		

        	String str1 = Integer.toString(a);
        	String str2 = Integer.toString(b);
        	String tmp = "쿠폰사용기간 : " + str1 + "월" + str2 + "일 까지";
        	text.setText(tmp);
        }
		
        //final ProgressDialog nowloding = ProgressDialog.show(hospital_mycoupon.this,"","내 쿠폰 정보를 불러오고 있습니다....",true);
        
        
        
        /*new Thread(new Runnable() {    
			@Override
			public void run() {
				items.coupon_list.removeAll(items.coupon_list);
				items.coupon_back = 1;
				
				URL url = null;
				String resultString =null;
				try {
				  	
					url = new URL(tour_mycoupon_call+"?app_type="+items.apptype+"&c_code="+items.c_code);
					
					HttpURLConnection http = (HttpURLConnection)url.openConnection();  
				
					BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
					StringBuffer buffer = new StringBuffer();
						 
					int c;  
						 
					while((c=in.read()) != -1){
						buffer.append((char)c);
					}
						
					resultString= buffer.toString().trim();
						
					XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
					factory.setNamespaceAware(true);
						  
					boolean tagok = false;
						  
					String[] coupon_call = null;
						  
					XmlPullParser xpp = factory.newPullParser();
					xpp.setInput(new StringReader(resultString));
						  
					int eventType = xpp.getEventType();
						  
					while (eventType != XmlPullParser.END_DOCUMENT) {
						      
						if(eventType == XmlPullParser.START_DOCUMENT) {
							System.out.println("Start document");
						}
						
						if (eventType == XmlPullParser.END_DOCUMENT) {
							System.out.println("End document");
						}
						
						if (eventType == XmlPullParser.START_TAG) {
							
							if(xpp.getName().equals("name")){
								tagok = true;
							}
						}
						
						if (eventType == XmlPullParser.END_TAG) {
						}
						
						if (eventType == XmlPullParser.TEXT) {
							if(tagok){
								coupon_call = xpp.getText().split("@");
							}
							coupons cps = new coupons(Integer.parseInt(coupon_call[0]),coupon_call[1],coupon_call[2],coupon_call[3],coupon_call[4],coupon_call[5],coupon_call[6],coupon_call[7],coupon_call[8],coupon_call[9],coupon_call[10]);
									
							items.coupon_list.add(cps);
						}
						eventType = xpp.next();
					}
					runOnUiThread(new Runnable(){
						@Override
						public void run() {
							CouponAdapter couponad = new CouponAdapter(hospital_mycoupon.this, R.layout.couponlistview, items.coupon_list);
							setListAdapter(couponad);
						}
					});
					nowloding.cancel();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					runOnUiThread(new Runnable(){
					    @Override
					     public void run() {
					    	nologin = new AlertDialog.Builder(hospital_mycoupon.this);
							nologin.setTitle(items.appname);
							nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
							nologin.setIcon(R.drawable.icon);
							nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
							@Override
								public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
												moveTaskToBack(true);
												android.os.Process.killProcess(android.os.Process.myPid());
											}
										});
							nologin.show();
						}
					});
					e.printStackTrace();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
	    }).start();
        
        getListView().setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				items.coupon_info_back = 1;
				items.coupon_position = position;
				
				AlertDialog.Builder coupon_use = new AlertDialog.Builder(hospital_mycoupon.this);
				coupon_use.setTitle(items.appname);
				coupon_use.setIcon(R.drawable.icon);
				coupon_use.setPositiveButton("쿠폰확인", new DialogInterface.OnClickListener(){
					@Override
						public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
							Intent intent = new Intent(hospital_mycoupon.this, tour_coupon_info.class);
							startActivityForResult(intent, 0);
							finish();
						}
					});
				coupon_use.setNeutralButton("쿠폰사용", new DialogInterface.OnClickListener(){
					@Override
						public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						System.out.println(items.coupon_list.get(items.coupon_position).getCoupon_no());
							Context mContext = getApplicationContext();
							LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(LAYOUT_INFLATER_SERVICE);
							final View editdial = inflater.inflate(R.layout.coupon_alertdialog_edit,(ViewGroup) findViewById(R.id.coupon_use_alertdialog));
							
							AlertDialog.Builder coupon_use_final = new AlertDialog.Builder(hospital_mycoupon.this);
							coupon_use_final.setTitle(items.appname);
							coupon_use_final.setIcon(R.drawable.icon);
							coupon_use_final.setView(editdial);
							coupon_use_final.setMessage("점포 쿠폰 번호를 입력하세요");
							coupon_use_final.setPositiveButton("쿠폰사용", new DialogInterface.OnClickListener(){
								@Override
									public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
										EditText insert_coupon_no = (EditText) editdial.findViewById(R.id.insert_coupon_no);
										
										if(insert_coupon_no.getText().toString().equals("")){
											Toast.makeText(hospital_mycoupon.this,"쿠폰번호를 입력해 주세요",Toast.LENGTH_SHORT).show();
										}else{
											if(items.coupon_list.get(items.coupon_position).getCoupon_no() ==  Integer.parseInt(insert_coupon_no.getText().toString())){
												final ProgressDialog nowloding = ProgressDialog.show(hospital_mycoupon.this,"","쿠폰을 확인하고 있습니다....",true);
												
												new Thread(new Runnable() {    
													@Override
													public void run() {
														URL url = null;
														String resultString =null;
														try {
														  	
															url = new URL(tour_mycoupon_delete+"?app_type="+items.apptype+"&c_code="+items.c_code+"&coupon_no="+items.coupon_list.get(items.coupon_position).getCoupon_no());
															
														    HttpURLConnection http = (HttpURLConnection)url.openConnection();  
														    BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));  
															
														    StringBuffer buffer = new StringBuffer();
																 
															int c;  
																 
															while((c=in.read()) != -1){
																buffer.append((char)c);
															}
																
															resultString= buffer.toString().trim();
															nowloding.cancel();
															
															if(resultString.equals("1")){
																runOnUiThread(new Runnable(){
																    @Override
																     public void run() {
																    	nologin = new AlertDialog.Builder(hospital_mycoupon.this);
																		nologin.setTitle(items.appname);
																		nologin.setMessage("쿠폰 확인이 완료 되었습니다");
																		nologin.setIcon(R.drawable.icon);
																		nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
																		@Override
																			public void onClick(DialogInterface dialog, int which) {
																			// TODO Auto-generated method stub
																				Intent intent = new Intent(hospital_mycoupon.this, hospital_mycoupon.class);
																				startActivityForResult(intent, 0);
																				finish();
																			}
																		});
																		nologin.show();
																    	
																    	
																	}
																});
															}
															
														} catch (MalformedURLException e) {
																// TODO Auto-generated catch block
															e.printStackTrace();
														} catch (IOException e) {
															// TODO Auto-generated catch block
															runOnUiThread(new Runnable(){
															    @Override
															     public void run() {
															    	nologin = new AlertDialog.Builder(hospital_mycoupon.this);
																	nologin.setTitle(items.appname);
																	nologin.setMessage("서버에 접속이 되지 않습니다\n네트워크를 확인 후 다시 시도해 주세요");
																	nologin.setIcon(R.drawable.icon);
																	nologin.setPositiveButton("확 인", new DialogInterface.OnClickListener(){
																	@Override
																		public void onClick(DialogInterface dialog, int which) {
																		// TODO Auto-generated method stub
																						moveTaskToBack(true);
																						android.os.Process.killProcess(android.os.Process.myPid());
																					}
																				});
																	nologin.show();
																}
															});
															e.printStackTrace();
														}
													}
											    }).start();
											}else{
												Toast.makeText(hospital_mycoupon.this,"쿠폰 번호를 확인 하세요",Toast.LENGTH_SHORT).show();
											}
										}
									}
								});
							coupon_use_final.setNegativeButton("취 소", null);
							coupon_use_final.show();
						}
					});
				coupon_use.setNegativeButton("취 소", null);
				coupon_use.show();
			}
		});
    }
    public class CouponAdapter extends ArrayAdapter<coupons> { 
		
    	private ArrayList<coupons> coupon_list; 
    	
    	public CouponAdapter(Context context, int textViewResourceId, ArrayList<coupons> coupon_list) { 
    		super(context, textViewResourceId, coupon_list); 
    		this.coupon_list = coupon_list;
    	}
        
    	public View getView(final int position, View convertView, ViewGroup parent) { 
    		View v = convertView; 
    		
    		if (v == null) {
    			LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);                   
    			v = vi.inflate(R.layout.mycouponlistview, null);
    		}       
    			
    		coupons cp = coupon_list.get(position);
    		
    	    URLConnection conn = null;
    		InputStream is= null;
    	        
    		if(cp != null){
    			TextView mycoupon_name_text = (TextView) v.findViewById(R.id.mycoupon_name_text);
    			TextView mycoupon_sevicelife_text = (TextView) v.findViewById(R.id.mycoupon_sevicelife_text);
    			TextView mycoupon_matter_text = (TextView) v.findViewById(R.id.mycoupon_matter_text);
    			TextView mycoupon_no_text = (TextView) v.findViewById(R.id.mycoupon_no_text);
    			
    			if(mycoupon_name_text != null){ mycoupon_name_text.setText(cp.getCoupon_subject());}
    			if(mycoupon_sevicelife_text != null){ mycoupon_sevicelife_text.setText("사용기간 : "+cp.getCoupon_servicelife());}
    			if(mycoupon_matter_text != null){ mycoupon_matter_text.setText("유의사항 : "+cp.getCoupon_matters());}
    			if(mycoupon_no_text != null){ mycoupon_no_text.setText(cp.getCoupon_no()+"");}
    		}
    			return v; */  
    }
	public boolean onKeyDown( int KeyCode, KeyEvent event ){
 		if( event.getAction() == KeyEvent.ACTION_DOWN ){
 			if( KeyCode == KeyEvent.KEYCODE_BACK ){
 				Intent intent = new Intent(hospital_mycoupon.this, hospital_main.class);
 				startActivityForResult(intent, 0);
 				finish();
 				
 				return false;
 			}
 		}
 		return super.onKeyDown(KeyCode, event);
 	}
    /*public class CouponAdapter extends ArrayAdapter<coupons> { 
		
    	private ArrayList<coupons> coupon_list; 
    	
    	public CouponAdapter(Context context, int textViewResourceId, ArrayList<coupons> coupon_list) { 
    		super(context, textViewResourceId, coupon_list); 
    		this.coupon_list = coupon_list;
    	}
        
    	public View getView(final int position, View convertView, ViewGroup parent) { 
    		View v = convertView; 
    		
    		if (v == null) {
    			LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);                   
    			v = vi.inflate(R.layout.mycouponlistview, null);
    		}       
    			
    		coupons cp = coupon_list.get(position);
    		
    	    URLConnection conn = null;
    		InputStream is= null;
    	        
    		if(cp != null){
    			TextView mycoupon_name_text = (TextView) v.findViewById(R.id.mycoupon_name_text);
    			TextView mycoupon_sevicelife_text = (TextView) v.findViewById(R.id.mycoupon_sevicelife_text);
    			TextView mycoupon_matter_text = (TextView) v.findViewById(R.id.mycoupon_matter_text);
    			TextView mycoupon_no_text = (TextView) v.findViewById(R.id.mycoupon_no_text);
    			
    			if(mycoupon_name_text != null){ mycoupon_name_text.setText(cp.getCoupon_subject());}
    			if(mycoupon_sevicelife_text != null){ mycoupon_sevicelife_text.setText("사용기간 : "+cp.getCoupon_servicelife());}
    			if(mycoupon_matter_text != null){ mycoupon_matter_text.setText("유의사항 : "+cp.getCoupon_matters());}
    			if(mycoupon_no_text != null){ mycoupon_no_text.setText(cp.getCoupon_no()+"");}
    		}
    			return v;   
    	}	
    
    public boolean onKeyDown( int KeyCode, KeyEvent event ){
		if( event.getAction() == KeyEvent.ACTION_DOWN ){
			if( KeyCode == KeyEvent.KEYCODE_BACK ){
				Intent intent = new Intent(hospital_mycoupon.this, hospital_main.class);
				startActivityForResult(intent, 0);
				finish();
				
				return false;
			}
		}
		return super.onKeyDown(KeyCode, event);
	}*/
}
